import { Component, OnInit } from '@angular/core';
import { UserService } from '../../shared/services/user.service';
import { SelectItem, Message } from 'primeng/api';
import { UserStatus, UserRoles, CRUD_MODE } from '../../shared/config/app-settings';
import { CountryUtilsService } from '../../shared/services/country-utils.service';
import { ActivatedRoute } from '@angular/router';
import { AttachmentUtilsService } from '../../shared/services/attachment-utils.service';
import { MessageUtilsService } from '../../shared/services/message-utils.service';
import * as _ from 'lodash';
import { state } from '@angular/animations';
import { AppUtilsService } from '../../shared/services/app-utils.service';
@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.scss']
})
export class UserProfileComponent implements OnInit {

  meta = {
    mode: '',
    role: ''
  }

  currentProfile: any = UserService.defaultProfile;
  msgs: Message[] = [];
  isActiveDiv: boolean = false;
  currentSessionUser: any = {};
  statusOptions: SelectItem[];
  roleOptions: SelectItem[];
  sexOptions: SelectItem[];
  referIDOptions: SelectItem[];
  experienceOptions: SelectItem[];
  cdropDownOptions = this.countryUtilsService.dropDownOptions;
  cdropDownSelected = this.countryUtilsService.dropDownSelected;
  constructor(private userService: UserService,
    private countryUtilsService: CountryUtilsService,
    private route: ActivatedRoute,
    private appUtilsService: AppUtilsService,
    private attachmentUtilsService: AttachmentUtilsService,
    private messageUtilsService: MessageUtilsService) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.currentProfile.id = params['id'];
    });

    this.route.queryParams.subscribe(params => {
      this.meta.mode = params['mode'];
      this.meta.role = params['role'];
      console.log(this.meta);
    });

    this.statusOptions = [
      { label: UserStatus.ACTIVE, value: UserStatus.ACTIVE },
      { label: UserStatus.PENDING, value: UserStatus.PENDING },
      { label: UserStatus.INACTIVE, value: UserStatus.INACTIVE },
      { label: UserStatus.DRAFT, value: UserStatus.DRAFT },
    ];
    this.roleOptions = [
      { label: UserRoles.ADMIN, value: UserRoles.ADMIN },
      { label: UserRoles.AGENT, value: UserRoles.AGENT },
      { label: UserRoles.CUSTOMER, value: UserRoles.CUSTOMER }
    ];
    this.experienceOptions = [
      { label: 'None', value: 'None' },
      { label: '1-2 Years', value: '1-2 Years' },
      { label: '2-5 Years', value: '2-5 Years' },
      { label: '5+ Years', value: '5+ Years' }
    ];
    this.sexOptions = [
      { label: "Male", value: "Male" },
      { label: "Female", value: "Female" }
    ];

    this.getCurrentUser();


    this.userService.getUserList({}).subscribe((res) => {
      // let x = _.chain(res).filter((user)=> this.userService.isActive(user));

      this.referIDOptions = _.chain(res)
        .filter((user) => {
          return this.userService.isActive(user) && user.role === UserRoles.AGENT
        })
        .sortBy('role')
        .map((user) => { return { label: this.userService.getFullName(user), value: user.code } })
        .value();
    });
    this.loadCurrentProfile();

  }

  loadCurrentProfile() {
    if (this.currentProfile.id === 0) {
      //0 id means create.
      this.enrichResponse();
      return;
    }
    this.userService.getUserById(this.currentProfile.id).subscribe(
      (res) => {
        this.currentProfile = res;
        this.enrichResponse();
      }
    );
  }

  getTCString() {
    if (this.currentProfile.acceptTCVersion && this.currentProfile.acceptTCTime)
      return `User accepted iPAN Terms & Conditions version ${this.currentProfile.acceptTCVersion} on ${this.currentProfile.acceptTCTime}`
    else
      return '';
  }

  getCurrentUser() {
    this.userService.getCurrentUser().subscribe((user) => {
      this.currentSessionUser = user;
      this.setEditableAll();
    });
  }


  onFileUpload(belongToCategory, fileUploader, entity, deleteOrigin = false) {
    let attachment = {
      entity: entity,
      belongToID: this.currentProfile.id,
      belongToCategory: belongToCategory,
      files: fileUploader.files
    };
    this.attachmentUtilsService.uploadFile(attachment, deleteOrigin).subscribe(
      (res) => {
        this.messageUtilsService.showInfo(this.msgs, " Attahement update success");
        fileUploader.clear();
        this.loadCurrentProfile();
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs, "Operation Failed.");
      }
    );
  }

  onDeleteFile(attachment) {
    this.attachmentUtilsService.deleteFile(attachment.id).subscribe(
      (res) => {
        this.loadCurrentProfile();
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs, "Operation Failed.");
      }
    );
  }

  addProfile() {
    if (this.valid()) {
        console.log(this.messageUtilsService)
      this.messageUtilsService.showError(this.msgs, this.valid());
      return;
    }
    this.enrichRequestProfile();
    console.log(this.currentProfile);
    this.userService.addUser(this.currentProfile).subscribe(
      (res) => {
        console.log('create user success', res);
        alert("Success");
        history.back();
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs, "Operation Failed.");
      }
    );
  }

  updateProfile() {
    if (this.valid()) {
      this.messageUtilsService.showError(this.msgs, this.valid());
      return;
    }
    this.enrichRequestProfile();
    this.userService.updateUser(this.currentProfile).subscribe(
      (res) => {
        console.log(res);
        console.log('update user success', res);
        alert("success");
        history.back();
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs, "Operation Failed.");
      }
    );
  }

  valid() {
    let errMsg = '';
    if (this.meta.mode === CRUD_MODE.CREATE) {
      if (!this.currentProfile.firstName) errMsg += 'firstName invalid. ';
      if (!this.currentProfile.privateEmail) errMsg += 'privateEmail invalid. ';
      if (!this.currentProfile.lastName) errMsg += 'lastName invalid. ';
      if (!this.currentProfile.referID) errMsg += 'referID invalid. ';

    } else {
      if (!this.currentProfile.firstName) errMsg += 'firstName invalid. ';
      if (!this.currentProfile.privateEmail) errMsg += 'privateEmail invalid. ';
      if (!this.currentProfile.lastName) errMsg += 'lastName invalid. ';
      if (!this.currentProfile.password) errMsg += 'password invalid. ';
      if (!this.currentProfile.status) errMsg += 'status invalid. ';
      if (!this.currentProfile.referID) errMsg += 'referID invalid. ';

      if (this.currentProfile.password !== this.currentProfile.newPasswordRepeat) {
        errMsg += 'Password not match. ';
      }
    }
    console.log('errMsg', errMsg);
    return errMsg;
  }

  enrichRequestProfile() {
    if (this.meta.mode === CRUD_MODE.CREATE) {
      this.currentProfile.role = this.meta.role;
      this.currentProfile.status = 'pending'; //in order to approve in java side
    }

    // this.currentProfile.birth = this.appUtilsService.dateToString(this.currentProfile._birth);
    this.currentProfile.country = this.countryUtilsService.getSelectedCountry();
    this.currentProfile.state = this.countryUtilsService.getSelectedState();
    this.currentProfile.city = this.countryUtilsService.getSelectedCity();
    // this.currentProfile.email = this.currentProfile.firstName + '.' + this.currentProfile.lastName + '@ipanproperty.com';
  }

  enrichResponse() {
    this.currentProfile.newPasswordRepeat = this.currentProfile.password;
    this.currentProfile.birth = this.appUtilsService.stringToDate(this.currentProfile.birth);
    this.currentProfile.createTime = this.currentProfile.createTime ? new Date(this.currentProfile.createTime) : new Date();
    this.countryUtilsService.constructDropDownOptions(this.currentProfile.country, this.currentProfile.state, this.currentProfile.city);
  }

  onRreshDropDownOptions(event) {
    this.countryUtilsService.refreshDropDownOptions();
    console.log(this.cdropDownSelected);
  }

  getCRUD() {
    return this.currentProfile.id >= 1 ? CRUD_MODE.EDIT : CRUD_MODE.CREATE;
  }

  //allow editing
  isEdit() {
    return this.meta.mode === CRUD_MODE.EDIT;
  }

  isViewMode() {
     return this.meta.mode !== CRUD_MODE.EDIT && this.meta.mode !== CRUD_MODE.CREATE;
  }

  getMaskString(digits: string) {
      if (digits && digits.length >= 4) {
          const firstTwoLetters = digits.substring(0, 2);
          const lastTwoLetters = digits.substring(digits.length - 2);
          const middleLetters = digits.substring(2 , digits.length - 2).replace(/./g, '*');
          return  firstTwoLetters + middleLetters + lastTwoLetters ;
      }
      return digits;
      // return digits.replace(/(?<=..).(?=..)/g, '**$1**');
  }

  getUserPhoto() {
    let portraits = this.currentProfile.user_portrait || [];
    return portraits[0] || {};
  }

  getTitle() {
    return `${_.upperCase(this.meta.mode)}  ${this.currentProfile.firstName || ''} ${this.currentProfile.lastName || ''}`
  }

  setEditableAll() {
    this.isActiveDiv = this.currentSessionUser.role === UserRoles.ADMIN;
  }




}
